﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="Template.cs" company="Anton Frattaroli">
//   Copyright (c) Anton Frattaroli. All rights reserved.
// </copyright>
// <summary>
//   Defines the Template class.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace Lidocaine
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Data.SqlClient;
    using System.Globalization;

    /// <summary>
    /// Defines the Template class.
    /// </summary>
    public class Template
    {
        #region Fields
        /// <summary>
        /// The identity of the database table's row where this template object is saved.
        /// </summary>
        private int templateID;

        /// <summary>
        /// Stores the template type for this template (Header or Footer).
        /// </summary>
        private TemplateArea templateType;

        /// <summary>
        /// Stores the template's given name.
        /// </summary>
        private string templateName;

        /// <summary>
        /// Stores the template's actual content.
        /// </summary>
        private string templateText;
        #endregion

        #region Constructors
        /// <summary>
        /// Initializes a new instance of the Template class.
        /// </summary>
        public Template()
        {
        }

        /// <summary>
        /// Initializes a new instance of the Template class.
        /// </summary>
        /// <param name="templateId">The identity of the database table's row referencing this template.</param>
        public Template(int templateId)
        {
            using (SqlConnection conn = new SqlConnection(Environmental.ConnectionString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("Lidocaine.GetTemplateByID", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@ID", templateId);
                    using (SqlDataReader rdr = cmd.ExecuteReader())
                    {
                        if (rdr.HasRows)
                        {
                            rdr.Read();
                            this.templateID = templateId;
                            this.templateType = rdr["TemplateType"].ToString() == "True" ? TemplateArea.Header : TemplateArea.Footer;
                            this.templateName = (string)rdr["TemplateName"];
                            this.templateText = rdr["TemplateText"].ToString();
                        }
                        else
                        {
                            throw new DataException("Template does not exist.");
                        }
                    }
                }
            }
        }
        #endregion

        #region Properties
        /// <summary>
        /// Gets the template's database row identity.
        /// </summary>
        public int TemplateId
        {
            get
            {
                return this.templateID;
            }
        }

        /// <summary>
        /// Gets or sets the template's given name.
        /// </summary>
        public string TemplateName
        {
            get
            {
                return this.templateName;
            }

            set
            {
                this.templateName = value;
            }
        }

        /// <summary>
        /// Gets or sets the template's content.
        /// </summary>
        public string TemplateText
        {
            get
            {
                return this.templateText;
            }

            set
            {
                this.templateText = value;
            }
        }

        /// <summary>
        /// Gets or sets the template's type.
        /// </summary>
        public TemplateArea TemplateType
        {
            get
            {
                return this.templateType;
            }

            set
            {
                this.templateType = value;
            }
        }
        #endregion

        #region Methods
        /// <summary>
        /// Gets a dictionary of templates for the current application (determined by the connection's sql user account.)
        /// </summary>
        /// <param name="templateType">The type of templates to return (Header or Footer).</param>
        /// <returns>A dictionary object containing row identity keys and the referenced template's given name.</returns>
        public static Dictionary<int, string> GetTemplates(TemplateArea templateType)
        {
            Dictionary<int, string> templates = new Dictionary<int, string>();
            using (SqlConnection conn = new SqlConnection(Environmental.ConnectionString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("Lidocaine.GetTemplates", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@TemplateType", templateType == TemplateArea.Header ? 1 : 0);
                    using (SqlDataReader rdr = cmd.ExecuteReader())
                    {
                        if (rdr.HasRows)
                        {
                            while (rdr.Read())
                            {
                                templates.Add(Convert.ToInt32(rdr["TemplateID"], CultureInfo.InvariantCulture), (string)rdr["TemplateName"]);
                            }
                        }
                    }
                }
            }

            return templates;
        }

        /// <summary>
        /// Inserts the HTemplate object into the database.
        /// </summary>
        public void SaveAs()
        {
            using (SqlConnection conn = new SqlConnection(Environmental.ConnectionString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("Lidocaine.InsertTemplate", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@TemplateType", this.templateType == TemplateArea.Header ? 1 : 0);
                    cmd.Parameters.AddWithValue("@TemplateName", this.templateName);
                    this.templateID = Convert.ToInt32(cmd.ExecuteScalar(), CultureInfo.InvariantCulture);
                }
            }
        }

        /// <summary>
        /// Updates the HTemplate's database fields.
        /// </summary>
        public void Save()
        {
            using (SqlConnection conn = new SqlConnection(Environmental.ConnectionString))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("Lidocaine.UpdateTemplate", conn))
                {
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.AddWithValue("@TemplateID", this.templateID);
                    cmd.Parameters.AddWithValue("@TemplateName", this.templateName);
                    cmd.Parameters.AddWithValue("@TemplateText", this.templateText);
                    cmd.ExecuteNonQuery();
                }
            }
        }

        /// <summary>
        /// Deletes the HTemplate's database entry.
        /// </summary>
        public void Delete()
        {
            using (SqlConnection conn = new SqlConnection(Environmental.ConnectionString))
            {
                conn.Open();
                if (this.templateType == TemplateArea.Header)
                {
                    using (SqlCommand cmd = new SqlCommand("Lidocaine.DeleteHeader", conn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@ID", this.templateID);
                        cmd.ExecuteNonQuery();
                    }
                }
                else if (this.templateType == TemplateArea.Footer)
                {
                    using (SqlCommand cmd = new SqlCommand("Lidocaine.DeleteFooter", conn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@ID", this.templateID);
                        cmd.ExecuteNonQuery();
                    }
                }
            }
        }

        /// <summary>
        /// Gets the titles of pages related to this template.
        /// </summary>
        /// <returns>A readonly list of the titles of the pages referencing this template.</returns>
        public IList<string> GetPages()
        {
            List<string> pages = new List<string>();
            using (SqlConnection conn = new SqlConnection(Environmental.ConnectionString))
            {
                conn.Open();
                if (this.templateType == TemplateArea.Header)
                {
                    using (SqlCommand cmd = new SqlCommand("Lidocaine.GetHeaderPages", conn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@ID", this.templateID);
                        using (SqlDataReader rdr = cmd.ExecuteReader())
                        {
                            if (rdr.HasRows)
                            {
                                while (rdr.Read())
                                {
                                    if (rdr["Name"] == DBNull.Value)
                                    {
                                        pages.Add(string.Empty);
                                    }
                                    else
                                    {
                                        pages.Add((string)rdr["Name"]);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    using (SqlCommand cmd = new SqlCommand("Lidocaine.GetFooterPages", conn))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;
                        cmd.Parameters.AddWithValue("@ID", this.templateID);
                        using (SqlDataReader rdr = cmd.ExecuteReader())
                        {
                            if (rdr.HasRows)
                            {
                                while (rdr.Read())
                                {
                                    if (rdr["Name"] == DBNull.Value)
                                    {
                                        pages.Add(string.Empty);
                                    }
                                    else
                                    {
                                        pages.Add((string)rdr["Name"]);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return pages.AsReadOnly();
        }
        #endregion
    }
}